package com.joplus.housekeeper.utils;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * ListView 万能适配器的ViewHolder  
 * 用于ListView Item View 的重复利用
 * @author tangdehao
 *
 */
public class ViewHolder {
	private SparseArray<View> mViews;
	private int mPostion;
	private View mConvertView;

	public ViewHolder(Context context, ViewGroup parent, int layoutId,
			int position) {

		mViews = new SparseArray<View>();
		this.mPostion = position;
		this.mConvertView = LayoutInflater.from(context).inflate(
				layoutId, parent, false);

		this.mConvertView.setTag(this);
	}

	public static ViewHolder get(Context context, View convertView,
			ViewGroup parent, int layoutId, int position) {
		if (convertView == null) {
			return new ViewHolder(context, parent, layoutId, position);
		} else {
			ViewHolder holder = (ViewHolder) convertView.getTag();
			
			holder.mPostion = position;
			return holder;
		}
	}
		
	/**
	 * ͨ��viewId��ȡ�ؼ�
	 * @param viewId
	 * @return
	 */
	public <T extends View> T getView(int viewId) {
		View view = mViews.get(viewId);
		
		if (view == null) {
			view = mConvertView.findViewById(viewId);
			
			mViews.put(viewId, view);
		}
		
		return (T) view;
	}
	
	public View getConvertView() {
		return mConvertView;
	}

	public ViewHolder setText(int viewId,String text){
		TextView textView  = getView(viewId);
		textView.setText(text);
		return this;
	}
	public int getPostion() {
		return mPostion;
	}
}
